import express from "express"
import cors from "cors"
import multer  from "multer"
import fs, { writeFile } from "fs"
import path from "path"

// 设置文件接收的配置
const storage = multer.diskStorage({
    // 放入地址
    destination:function(req,file,cb){
        cb(null,"uploads/")
    },
    // 设置文件名
    filename:function(req,file,cb){
        cb(null,`${req.body.id}-${req.body.fileName}`)
    }
})

const upload = multer({storage})



const app = express()
app.use(cors())
app.use(express.json())

app.post('/upload',upload.single('file'),(req,res)=>{
    res.send({
        msg:"文件上传成功"
    })
})

app.post('/uploadEnd',(req,res)=>{
    // 获取uploads下面的文件碎片
    const filePath = path.join(process.cwd(),"uploads")
    let files = fs.readdirSync(filePath)
    files =  files.sort((a,b)=>a.split("-")[0] - b.split("-")[0])

    // 提供写入地址
    const writePath = path.join(process.cwd(),"video",`${req.body.fileName}.mp4`)
    
    // 合并文件
    files.forEach(file=>{
        // 写入文件
        fs.appendFileSync(writePath,fs.readFileSync(path.join(process.cwd(),"uploads",file)))
        // 删除文件
        fs.unlinkSync(path.join(process.cwd(),"uploads",file))
    })

    res.send({
        msg:"文件上传成功！"
    })
})

app.listen(3000,()=>{
    console.log("http://localhost:3000 ");
})